package com.webserver.http;

import com.sun.org.glassfish.external.statistics.Statistic;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.security.cert.Extension;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 该类定义所有和HTTP协议有关可被复用的数据信息
 * @Author Alex
 */
public class HttpContext {
    /**
     * 回车符
     */
    public static final char CR = 13;
    /**
     * 换行符
     */
    public static final char LF = 10;


    /**
     * 存放所有资源的后缀与Content-Type头的对应关系
     * key:资源的后缀名
     * value:Content-Type头对应的值
     */
    private static Map<String,String> mimeMapping = new HashMap<>();

    static{
        //初始化mimeMapping
            initMimeMapping();
    }

    /**
     * 初始化mimeMapping
     */
    private static void initMimeMapping() {
//        mimeMapping.put("html","text/html");
//        mimeMapping.put("css","text/css");
//        mimeMapping.put("js","application/javascript");
//        mimeMapping.put("png","image/png");
//        mimeMapping.put("gif","image/gif");
//        mimeMapping.put("jpg","image/jpeg");
        /*
            通过解析config目录下的web.xml文件,将根标签下所有名为<mime-mapping>的
            子标签获取到,并将其中的子标签:
            <extension>中间的文本作为key
            <mime-type>中间的文本作为value
            存入mimeMapping中完成初始化
         */

        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read("./config/web.xml");
            Element root = doc.getRootElement();

            List<Element> mimeList = root.elements("mime-mapping");
            for (Element webEle:mimeList){
                mimeMapping.put(webEle.elementText("extension"),webEle.elementText("mime-type"));
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据资源后缀名获取对应的Content-Type头信息
     * @param ext
     * @return
     */
    public static String getMimeType(String ext){
        return mimeMapping.get(ext);
    }

}
